﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.HeaEncyclopeCommand;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.HeaEncyclopeHarder
{
    public class GetHeaEncyclopeHarder : IRequestHandler<GetHeaEncyclopeCommand,APIPaging<HeaEncyclope>>
    {

        private readonly IBaseRepository<HeaEncyclope> repository;
        private readonly ILogger<GetHeaEncyclopeHarder> logger;

        public GetHeaEncyclopeHarder(IBaseRepository<HeaEncyclope> repository, ILogger<GetHeaEncyclopeHarder> logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        public async Task<APIPaging<HeaEncyclope>> Handle(GetHeaEncyclopeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIPaging<HeaEncyclope> result = new APIPaging<HeaEncyclope>();
                result.Code = APIEnum.Mvc;
                result.Msg = "查询成功";
                var list = repository.GetAll();
                // 应用筛选条件
                if (!string.IsNullOrEmpty(request.Titlearticle))
                {
                    list = list.Where(x => x.Titlearticle.Contains(request.Titlearticle));
                }

             
                result.Count = list.Count();
                result.PageCount = (int)Math.Ceiling(result.Count * 1.0 / request.PageSize);
                result.Data = list.OrderByDescending(a => a.HeaId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        
        }
    }
}
